package com.accesshollywood.indexables;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.LinkedHashMap;

import sqlUtility.SQLUtility;

import com.accesshollywood.SQL.GFXSQL;
import com.accesshollywood.viewFiltering.ViewFilter;
import com.accesshollywood.viewFiltering.ViewFilters;

public class ViewFilterMap extends AbstractIndexedMap {
	// protected LinkedHashMap<Integer, ViewFilter> checkedFilters = new LinkedHashMap<Integer, ViewFilter>();
	protected LinkedHashMap<Integer, ViewFilter>	map	= new LinkedHashMap<Integer, ViewFilter>();

	public ViewFilterMap() {
		this.map = super.map;
	}

	@Override
	public void initSQL() {
		setThat(this);
		tableName = "ViewFilterList";
		idColumnName = "idViewFilterList";
		elementColumnName.put(getField("map"), "idViewFilter");
	}

	public int toSQL() {
		if (!this.isIndexed()) {
			try {
				this.setId(SQLUtility.getNextAvailableID(tableName));
				// GFXSQL.addObject(tableName, idColumnName, this.getId());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		Iterator itr = iterator();
		while (itr.hasNext()) {
			ViewFilter currFilter = (ViewFilter) itr.next();
			if (!GFXSQL.exists(tableName, new Object[] { "idViewFilterList", "idViewFilter" }, new Object[] { this.getId(), currFilter.getId() })) {
				GFXSQL.addInts(tableName, new Object[] { "idViewFilterList", "idViewFilter" }, new Object[] { this.getId(), currFilter.getId() });
			}
		}

		return this.getId();
	}

	public void fromSQL() {
		// hijack the fromSQL method to keep it from trying to load something that doesn't actually exist.
		ResultSet rawViewFilterList = GFXSQL.getResultSet("ViewFilterList", "*", "idViewFilterList = " + this.getId());
		try {
			while (rawViewFilterList.next()) {
				int idViewFilter = rawViewFilterList.getInt("idViewFilter");
				ViewFilter savedFilter = ViewFilters.allViewFilters.get(idViewFilter);
				LinkedHashMap test = ViewFilters.allViewFilters;
				if (savedFilter != null) {
					// this.checkedFilters.put(savedFilter.hashCode(), savedFilter);
					this.put(savedFilter.hashCode(), savedFilter);
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
